#include "utils/meven.h"
#include <stdio.h>
#include <time.h>
#include "landload/game.h"
#include "landload/landload.h"
#include "landload/req.h"
#include "auth/auth.h"
#include "utils/log.h"
#include <sys/socket.h>

void onAccept(even_detail *event, char* data, int size) {
    printf("%s:%d connect", event->address, event->port);
}

void onData(even_detail *event, char* data, int size) {
    log_info("%s:%d data %s", event->address, event->port, data);
    cJSON* resp = http_create_response(RESPONSE_NOT_FOUND, "not found", NULL);
    char* json = cJSON_Print(resp);
    send(event->fd, json, strlen(json), 0);
    free(json);
    cJSON_Delete(resp);
    return;
}

void onClose(even_detail *event, char* data, int size) {
    log_debug("%s:%d close", event->address, event->port);
}

void onListen(even_detail *event, char* data, int size) {
    log_info("listening on %d", event->port);
}

void onTimeout(even_detail *event, char* data, int size) {
    // 处理超时事件
    send(event->fd, data, size, 0);
    log_debug("%s:%d timeout", event->address, event->port);
}

void onHttp(even_detail *event, http_request_t *request) {
    char * data = cJSON_Print(request->body);
    // 处理http get请求
    log_debug("%s:%d request %s\n%s", event->address, event->port, request->header.path.data, data);
    free(data);
    return;
}

int main(int argc, char const *argv[]) {
    log_set_level(LOG_DEBUG);
    landload_init();
    load_user_db();
    log_info("db init success");
    meven_t* meven = meven_init();

    meven_setCallback(meven, EVENT_ACCEPT, onAccept);
    meven_setCallback(meven, EVENT_DATA, onData);
    meven_setCallback(meven, EVENT_CLOSE, onClose);
    meven_setCallback(meven, EVENT_LISTEN, onListen);
    meven_setCallback(meven, EVENT_TIMEOUT, onTimeout);
    
    meven_setMethod(meven, MEVEN_HTTP_GET, "/game/status", getGameStatus);
    meven_setMethod(meven, MEVEN_HTTP_POST, "/game/robload", getRobot);
    meven_setMethod(meven, MEVEN_HTTP_POST, "/game/cardout", getOutCard);
    meven_setMethod(meven, MEVEN_HTTP_POST, "/game/cardoutpass", outCardPass);
    meven_setMethod(meven, MEVEN_HTTP_POST, "/game/create_room", create_room);
    meven_setMethod(meven, MEVEN_HTTP_POST, "/game/join_room", join_room);
    meven_setMethod(meven, MEVEN_HTTP_GET, "/game/room_list", get_room_list);
    meven_setMethod(meven, MEVEN_HTTP_POST, "/game/quit_game", quit_game);
    meven_setMethod(meven, MEVEN_HTTP_POST, "/game/setStatus", setStatus);

    meven_setMethod(meven, MEVEN_HTTP_POST, "/auth/login", auth_login);
    meven_setMethod(meven, MEVEN_HTTP_POST, "/auth/register", auth_register);

    //meven_add_router(meven, "/game/set", onHttp);

    meven_listen(meven, 8080);

    meven_loop(meven);
    return 0;
}